import java.io.*;
import java.nio.charset.StandardCharsets;

public class Test {
    public static void main(String[] args) throws IOException {
        // Writer 是 Java 标准库提供的最基本的字符输出流
        // Writer 是一个抽象类，它是所有字符输出流的超类
        // 核心方法：write(int c)、write(char[] cbuf)、write(String str)
        // 所有数据先进入缓冲区，必须 flush() 或 close() 才真正写入磁盘

        writeCharByChar();      // 逐字符写
        writeWithEncoding();    // 指定编码，防止乱码
        bufferedWriteFile();    // 带缓冲 + 整行写
        stringWriterDemo();     // 内存模拟，类似 ByteArrayOutputStream
        printWriterDemo();      // PrintWriter 的 print/println 风格
    }

    /* 最原始：逐字符写 */
    public static void writeCharByChar() throws IOException {
        try (Writer writer = new FileWriter("out1.txt")) { // 默认平台编码
            String data = "Hello, 中文!";
            for (int i = 0; i < data.length(); i++) {
                writer.write(data.charAt(i)); // 一个 char 一个 char 地写
            }
            // 自动 close 会隐式 flush
        }
    }

    /* 指定编码：FileWriter 不能选编码，必须用 OutputStreamWriter 包一层 */
    public static void writeWithEncoding() throws IOException {
        try (Writer writer = new OutputStreamWriter(
                new FileOutputStream("out2.txt"), StandardCharsets.UTF_8)) {
            writer.write("指定 UTF-8 写入，避免中文乱码\n");
        }
    }

    /* 带缓冲，支持 newLine() 与整行写，性能高 */
    public static void bufferedWriteFile() throws IOException {
        try (BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(
                        new FileOutputStream("out3.txt"), StandardCharsets.UTF_8))) {
            bw.write("第一行");
            bw.newLine();               // 跨平台换行
            bw.write("第二行");
            bw.flush();                 // 手动刷一次
        }
    }

    /* 在内存中模拟 Writer，最后整体拿字符串 */
    public static void stringWriterDemo() throws IOException {
        try (StringWriter sw = new StringWriter()) {
            sw.write("Hello, ");
            sw.write("StringWriter!");
            String result = sw.toString(); // 一次性拿结果
            System.out.println("内存写出结果： " + result);
        }
    }

    /* PrintWriter 包装，支持 print/println/format，常用来替换 System.out */
    public static void printWriterDemo() throws IOException {
        try (PrintWriter pw = new PrintWriter(
                new OutputStreamWriter(
                        new FileOutputStream("out4.txt"), StandardCharsets.UTF_8))) {
            pw.println("print/println 风格");
            pw.printf("整数=%d, 字符串=%s%n", 123, "abc");
            // PrintWriter 构造器默认 autoFlush=false，这里没开，需要 close 才落盘
        }
    }
}